package com.echo.im.domain.group.manager;

import com.echo.im.common.result.ResultEnum;
import com.echo.im.common.contant.Constants;
import com.echo.im.common.exception.GlobalException;
import com.echo.im.repository.dao.entity.GroupMember;
import com.echo.im.repository.dao.mapper.GroupMemberMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

import java.util.Collection;
import java.util.List;
import java.util.Objects;

/**
 * @author: echo
 * @time: 2024-08-17
 */
@RequiredArgsConstructor
@Component
public class GroupMemberManager {

    private final GroupMemberMapper groupMemberMapper;


    public GroupMember findAndCheckMemberByGroupAndUserId(Long groupId, Long userId) {
        GroupMember member = groupMemberMapper.selectOneByGroupIdAndUserId(groupId, userId);
        if (Objects.isNull(member) || member.getQuit()) {
            throw new GlobalException(ResultEnum.NOT_MEMBER);
        }
        return member;
    }

    public List<Long> getReadedUserIds(Long groupId, Long ownerId, Long msgId) {

        List<Long> userIds=groupMemberMapper.selectReadedUserIds(groupId, msgId);

        userIds.remove(ownerId);

        return userIds;
    }

    /**
     * 校验群聊人数是否符合需要
     * @param needCount
     * @param groupId
     */
    public void checkMemberCount(Integer needCount,Long groupId) {
        // 群聊人数校验
        List<GroupMember> members = groupMemberMapper.selectListByGroupId(groupId);
        long size = members.stream().filter(m -> !m.getQuit()).count();
        if (needCount + size > Constants.MAX_GROUP_MEMBER) {
            throw new GlobalException(ResultEnum.OUT_OF_LIMIT_COUNT);
        }
    }

    public void updateLastAckMessageId(Long groupId,Long userId, Long lastAckMessageId) {
        groupMemberMapper.updateLastAckMessageIdByGroupIdAndUserId(groupId, userId, lastAckMessageId);
    }

    public Long findLastAckMessageIdByUserId(Long groupId, Long userId) {
        return groupMemberMapper.selectLastAckMessageIdByGroupIdAndUserId(groupId,userId);
    }

    public List<Long> findUserIdsByGroupId(Long groupId) {
        return groupMemberMapper.selectUserIdListByGroupId(groupId);
    }


    public void save(GroupMember member) {
        groupMemberMapper.insert(member);
    }

    public void updateById(GroupMember member) {
        groupMemberMapper.updateById(member);
    }

    public List<GroupMember> findByUserId(Long userId) {
        return groupMemberMapper.selectListByUserId(userId);
    }

    public Collection<? extends GroupMember> findQuitInMonth(Long userId) {
        return groupMemberMapper.selectQuitInMonth(userId);
    }

    public List<GroupMember> findByGroupId(Long groupId) {
        return groupMemberMapper.selectListByGroupId(groupId);
    }

    public void removeByGroupAndUserId(Long groupId, Long userId) {
        groupMemberMapper.deleteByGroupIdAndUserId(groupId, userId);
    }


}
